import { BrowserWindow, globalShortcut, screen } from 'electron'
import ConfigManager from './config-manager'

export const loadWindowState = (config: ConfigManager) => {
  const displays = screen.getAllDisplays()
  const destDisplay = displays[displays.length - 1]
  const { scaleFactor } = destDisplay

  if (config.windowState === '') {
    const width = Math.floor(destDisplay.bounds.width * 0.7)
    const height = Math.floor(destDisplay.bounds.height * 0.7)
    const x = destDisplay.bounds.x + Math.floor((destDisplay.bounds.width - width) / 2)
    const y = destDisplay.bounds.y + Math.floor((destDisplay.bounds.height - height) / 2)
    return { x, y, width, height, scaleFactor }
  }

  return {
    scaleFactor,
    ...JSON.parse(config.windowState),
  }
}

export const saveWindowState = (config: ConfigManager, mainWindow: BrowserWindow) => {
  const bounds = mainWindow.getBounds()
  if (mainWindow.isMaximized() || mainWindow.isMinimized()) {
    return
  }

  config.windowState = JSON.stringify({
    width: bounds.width,
    height: bounds.height,
    x: bounds.x,
    y: bounds.y,
  })
}

export const setupShortCut = (mainWindow: BrowserWindow, config: ConfigManager) => {
  globalShortcut.register('CommandOrControl+M', () => {
    const isVisible = mainWindow.isMenuBarVisible()
    mainWindow.setMenuBarVisibility(!isVisible)
    config.saveConfig('isMenuBarVisible', !isVisible ? 'true' : 'false')
  })
}
